<?php
/**
 * admin menus
 * when render menu both header and left
 * @package Admin Libraries
 * @author luweijun <yiming_6weijun@163.com>
 * @copyright (c) YouKeTang 2013 
 */
class Admin_Menu {
    
    /**
     * selected menu of top and left
     * @var null|Array
     */
    private static $selected = null;

    /**
     * get top selected menu of current request
     */
    public static function get_top() {
        list($top,$left) = static::_parse();
        return $top;
    }
    
    /**
     * get left selected menu of current request
     */
    public static function get_left() {
        list($top, $left) = static::_parse();
        return $left;
    }
    
    /**
     * get the memo for left menus
     */
    public static function get_memo() {
        $top = static::get_top();
        $menus = Config::get('admin.menu');
        if ($top != '' && array_key_exists($top, $menus)) {
            return $menus[$top]['name'];
        }
        return $menus['file']['name'];
    }
    
    /**
     * get menus of left
     */
    public static function get_left_menus() {
        $menus = Config::get('admin.menu');
        $top = static::get_top();
        $top = empty($top)?'file':$top;
        return $menus[$top]['nodes'];
    }
    
    /**
     * get dashboard
     */
    public static function get_dashboard() {
        $menus = Config::get('admin.menu');
        return $menus[static::get_top()];
    }

    /**
     * parse current url to fetch menu elements
     */
    private static function _parse() {
        if (null !== static::$selected)
            return static::$selected;
        
        static::$selected = array('','');
        $uri = URI::current();
        $prefix = 'admin';
        if (starts_with($uri,$prefix)) {
            $elements = explode('/', trim(substr($uri, strlen($prefix)),'/'));
            if(isset($elements[0]) && !empty($elements[0]) && $elements[0] != 'index') {
                if (array_key_exists($elements[0], Config::get('admin.menu'))) {
                     static::$selected = array($elements[0],  '');
                }
                foreach (Config::get('admin.menu') as $top=>$menus) {
                    if (isset($menus['nodes']) && array_key_exists($elements[0], $menus['nodes'])) {
                        static::$selected = array($top, $elements[0]);
                        break;
                    }
                }
            }
        }
        return static::$selected;
    }
    
}